import { CategoryService } from './../../service/category.service';
import { Restful, Router, Group, Autowire } from "ts-express-restful";
import { Request, Response, NextFunction } from "express-serve-static-core";
import Website from "../../model/website.model";
import { StorageFactory } from "../../service/storage";
import { cacheRemoveAll } from "../../service";
import { ArticleService } from "../../service/article.service";
import { WebsiteService } from '../../service/website.service';

@Group("admin")
@Restful()
export default class WebsiteController { 
    @Autowire
    public articleService!: ArticleService;
    @Autowire
    public categoryService!: CategoryService;
    @Autowire
    public websiteService!: WebsiteService;
    private keys: string[] = ['name', 'description', 'header', 'footer', 'copyright'];

    @Router('/setting', 'POST')
    async setting(req: Request, res: Response, next: NextFunction) { 
        let obj = req.body;
        let savedObj: any = {};
        let itemKeys = Object.keys(obj);
        let ps = itemKeys.map(async (key) => { 
            let m: Website | undefined = undefined;
            if (this.keys.indexOf(key) >= 0) {
                m = await this.websiteService.findOne({
                    where: {
                        key,
                    }
                });
                if (m) {
                    m.value = obj[key];
                } else { 
                    m = new Website();
                }
                m.key = key;
                m.value = obj[key];
                m = await this.websiteService.save(m);

            }
            savedObj[key] = m && m.value || null;
        })
        await Promise.all(ps);
        res.json(savedObj);
    }

    @Router('/setting')
    async findAllSetting(req: Request, res: Response, next: NextFunction) { 
        let ret: any = {};
        let ps = this.keys.map(async (key) => {
            let obj = await this.websiteService.findOne({
                where: {
                    key: key,
                }
            })
            ret[key] = obj && obj.value || '';
        });
        await Promise.all(ps);
        res.json(ret);
    }

    @Router('/cache', 'delete')
    async clearCache(req: Request, res: Response, next: NextFunction) { 
        await cacheRemoveAll();
        res.json(true);
    }
}